package com.zdp.io.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @Author zhengdp
 * @Description
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> {
    /**
     * 连接成功后的回调方法
     * @param result  ----> 新的连接Socket
     *          The result of the I/O operation.
     * @param attachment
     *          The object attached to the I/O operation when it was initiated.
     */
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        // 处理下一个连接事件 ---> 避免只处理一次连接
        attachment.asynchronousServerSocketChannel.accept(attachment,this);
        // 处理当前连接
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 异步读取连接的
        result.read(buffer,buffer,new ReadCompletionHandler(result));
    }

    /**
     * 连接失败后的回调方法
     * @param exc
     *          The exception to indicate why the I/O operation failed
     * @param attachment  ---> 附带对象
     *          The object attached to the I/O operation when it was initiated.
     */
    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}
